package com.qiantu.phone.ui.activity;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hjq.base.BaseAdapter;
import com.hjq.http.listener.HttpCallback;
import com.hjq.shape.drawable.ShapeDrawable;
import com.hjq.shape.drawable.ShapeType;
import com.qiantu.api.entity.LinkageBean;
import com.qiantu.api.entity.LinkageListBean;
import com.qiantu.api.entity.LinkageNewBean;
import com.qiantu.api.entity.LinkageStartStop;
import com.qiantu.api.entity.SceneDetailBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.ui.adapter.ListLabelAdapter;
import com.qiantu.phone.ui.adapter.SetLinkageAdapter;
import com.qiantu.phone.ui.adapter.SetLinkageAdapterNew;
import com.qiantu.phone.ui.dialog.BottomListDialog;
import com.qiantu.phone.utils.LinkageDataHolder;
import com.qiantu.phone.utils.TempDataHolder;
import com.lxj.xpopup.XPopup;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import okhttp3.Call;

/**
 * time   : 2021/12/22
 */
public final class LinkageStartStopActivityNew extends AppActivity {
    private int type;
    private int sceneType;
    private int pageIndex = 1;
    private int pageSize = Integer.MAX_VALUE;
    private EditText editSearch;
    private TextView tvSetLinkage;
    private TextView tvNotSetLinkage;
    private View setLayout;
    private RecyclerView setRecyclerView;
    private RecyclerView notSetRecyclerView;
    //已设置的子联动
    private SetLinkageAdapterNew mSetLinkageAdapter;
    //未设置的子联动
    private SetLinkageAdapterNew mNotSetLinkageAdapter;
    private BottomListDialog mBottomListDialog;
    //联动或者场景唯一编码
    private String serialNo;
    //联动
    private LinkageNewBean mLinkageBean;
    //场景
    private SceneDetailBean mSceneDetailBean;
    //联动任务
    private LinkageBean.LinkageTask mLinkageTask;
    //场景任务
    private SceneDetailBean.SceneTaskBean mSceneTask;
    //联动任务或者场景的子联动列表
    private List<LinkageStartStop> mLinkageStartStops;
    //当前点击选择已设置启停用的联动
    private LinkageListBean setStartStopLinkage;
    //当前点击选择未设置启停用的联动
    private LinkageListBean notSetStartStopLinkage;
    //所有联动
    private List<LinkageListBean> totalLinkageData;
    //未设置联动搜索结果
    private List<LinkageListBean> searchNotSetLinkageData;
    //已设置联动搜索结果
    private List<LinkageListBean> searchSetLinkageData;
    private int mPosition;
    private boolean isSet = false;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_linkage_start_stop;
    }

    @Override
    protected void initView() {
        type = getInt("type");
        sceneType = getInt("sceneType", 1);
        mPosition = getInt("position", -1);
        editSearch = findViewById(R.id.edit_search);
        tvSetLinkage = findViewById(R.id.tv_set_linkage);
        tvNotSetLinkage = findViewById(R.id.tv_not_set_linkage);
        setLayout = findViewById(R.id.set_layout);
        setRecyclerView = findViewById(R.id.set_recycler_view);
        notSetRecyclerView = findViewById(R.id.not_set_recycler_view);
        setRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        notSetRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mSetLinkageAdapter = new SetLinkageAdapterNew(getContext(), true, type);
        mSetLinkageAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
                setStartStopLinkage = mSetLinkageAdapter.getData().get(position);
                isSet = true;
                showBottomListDialog();
            }
        });
        mSetLinkageAdapter.setOnChildClickListener(R.id.check_view, new BaseAdapter.OnChildClickListener() {
            @Override
            public void onChildClick(RecyclerView recyclerView, View childView, int position) {
                LinkageListBean linkage = mSetLinkageAdapter.getItem(position);
                mSetLinkageAdapter.getData().remove(position);
                mSetLinkageAdapter.notifyDataSetChanged();
                mNotSetLinkageAdapter.removeSelectedBySerialNo(linkage.getLinkageSerialNo());
                isShowSetLinkageLayout();
            }
        });
        setRecyclerView.setAdapter(mSetLinkageAdapter);

        mNotSetLinkageAdapter = new SetLinkageAdapterNew(getContext(), false, type);
        mNotSetLinkageAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
                isSet = false;
                notSetStartStopLinkage = mNotSetLinkageAdapter.getItem(position);
                showBottomListDialog();
            }
        });
        notSetRecyclerView.setAdapter(mNotSetLinkageAdapter);
        editSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String keywords = s.toString();
                search(keywords);
            }
        });
        getLinkage();
        setNotSetRecyclerViewBg();
    }

    /**
     *NestedScrollView嵌套RecyclerView导致高度获取不到问题,阴影背景后设置才能显示
     */
    private void setNotSetRecyclerViewBg(){
        ShapeDrawable drawable = new ShapeDrawable();
        drawable.setShape(ShapeType.RECTANGLE)
                .setRadius(getResources().getDimensionPixelSize(R.dimen.dp_8), getResources().getDimensionPixelSize(R.dimen.dp_8), getResources().getDimensionPixelSize(R.dimen.dp_8), getResources().getDimensionPixelSize(R.dimen.dp_8))
                .setSolidColor(AppApplication.getInstance().getThemeColor(R.attr.shapeSolidColor));

        drawable.setShadowSize(getResources().getDimensionPixelSize(R.dimen.dp_4))
                .setShadowColor(AppApplication.getInstance().getThemeColor(R.attr.shapeShadowColor))
                .setShadowOffsetX(getResources().getDimensionPixelSize(R.dimen.dp_1))
                .setShadowOffsetY(getResources().getDimensionPixelSize(R.dimen.dp_1));
        notSetRecyclerView.setBackground(drawable);
    }

    private void search(String keywords){
        if(TextUtils.isEmpty(keywords)){
            mNotSetLinkageAdapter.setData(totalLinkageData);
            mSetLinkageAdapter.setData(mNotSetLinkageAdapter.getSelectedData());
            isShowSetLinkageLayout();
        }else{
            if(totalLinkageData != null && totalLinkageData.size() > 0){
                searchNotSetLinkage(keywords);
                searchSetLinkage(keywords);
            }
        }
    }

    private void searchNotSetLinkage(String keywords){
        if(searchNotSetLinkageData == null){
            searchNotSetLinkageData = new ArrayList<>();
        }else{
            searchNotSetLinkageData.clear();
        }
        for(LinkageListBean linkage: totalLinkageData){
            if(linkage.getName().contains(keywords)){
                searchNotSetLinkageData.add(linkage);
            }
        }
        mNotSetLinkageAdapter.setData(searchNotSetLinkageData);
    }

    private void searchSetLinkage(String keywords){
        if(searchSetLinkageData == null){
            searchSetLinkageData = new ArrayList<>();
        }else{
            searchSetLinkageData.clear();
        }
        for(LinkageListBean linkage: mNotSetLinkageAdapter.getSelectedData()){
            if(linkage.getName().contains(keywords)){
                searchSetLinkageData.add(linkage);
            }
        }
        mSetLinkageAdapter.setData(searchSetLinkageData);
        isShowSetLinkageLayout();
    }

    private void setCanSave(boolean isEnabled){
        getTitleBar().getRightView().setEnabled(isEnabled);
    }

    private void getLinkage(){
        //获取全部联动
        LLHttpManager.getLinkagesNew(this, pageIndex, pageSize, AppApplication.getInstance().getCurrentHouseSerialNo(), new HttpCallback<HttpData<List<LinkageListBean>>>(null) {
            @Override
            public void onStart(Call call) {
                showDialog();
            }

            @Override
            public void onSucceed(HttpData<List<LinkageListBean>> result) {
                totalLinkageData = result.getData();
                mNotSetLinkageAdapter.setData(totalLinkageData);
                updateView();
                if(mNotSetLinkageAdapter.getCount() > 0){
                    tvNotSetLinkage.setVisibility(View.VISIBLE);
                }else{
                    tvNotSetLinkage.setVisibility(View.GONE);
                }
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
            }

            @Override
            public void onEnd(Call call) {
                hideDialog();
            }
        });
    }

    @Override
    protected void initData() {
        serialNo = getString("serial_no");
        switch (type){
            case AddTaskActivity.TYPE_LINKAGE:
                mLinkageBean = LinkageDataHolder.getLinkageDataNew();
                if (mLinkageBean != null) {
                    List<LinkageBean.LinkageTask> linkageTasks = mLinkageBean.getLinkageTasks();
                    if (linkageTasks != null && linkageTasks.size() > 0 && !TextUtils.isEmpty(serialNo)) {
                        for (LinkageBean.LinkageTask item : linkageTasks) {
                            if (item.getTaskSerialNo() != null && item.getTaskSerialNo().equals(serialNo)) {
                                mLinkageTask = item;
                                mLinkageStartStops = mLinkageTask.getLinkageStartStop();
                                break;
                            }
                        }
                    }
                }
                break;
            case AddTaskActivity.TYPE_SCENE:
                mSceneDetailBean = TempDataHolder.getEditSceneDetailBean(sceneType);
                if (mSceneDetailBean != null) {
                    List<SceneDetailBean.SceneTaskBean> sceneTasks = mSceneDetailBean.getSceneTasks();
                    if (sceneTasks != null && sceneTasks.size() > 0 && !TextUtils.isEmpty(serialNo)) {
                        for (SceneDetailBean.SceneTaskBean item : sceneTasks) {
                            if (serialNo != null && serialNo.equals(item.getSceneTaskSerialNo())) {
                                mSceneTask = item;
                                mLinkageStartStops = mSceneTask.getLinkageStartStops();
                                break;
                            }
                        }
                    }
                }
                break;
        }
    }

    private void updateView(){
        if(mLinkageStartStops != null && mLinkageStartStops.size() > 0){
            mNotSetLinkageAdapter.checkSelectedBySerialNo(mLinkageStartStops);
            mSetLinkageAdapter.setData(mNotSetLinkageAdapter.getSelectedData());
            isShowSetLinkageLayout();
        }else{
            setCanSave(false);
        }
    }

    private void isShowSetLinkageLayout(){
        if(mSetLinkageAdapter.getCount() > 0){
            tvSetLinkage.setVisibility(View.VISIBLE);
            setLayout.setVisibility(View.VISIBLE);
        }else{
            tvSetLinkage.setVisibility(View.GONE);
            setLayout.setVisibility(View.GONE);
        }
        setCanSave(mNotSetLinkageAdapter.getSelectedData().size() > 0);
    }

    @Override
    public void onRightClick(View view) {
        List<LinkageListBean> linkageBeans = mNotSetLinkageAdapter.getSelectedData();
        if(linkageBeans == null || linkageBeans.size() == 0){
            return;
        }
        List<LinkageStartStop> linkageStartStops = new ArrayList<>();
        for(LinkageListBean linkageBean : linkageBeans){
            LinkageStartStop linkageStartStop = new LinkageStartStop();
            linkageStartStop.setLinkageSerialNo(linkageBean.getLinkageSerialNo());
            linkageStartStop.setLinkageName(linkageBean.getName());
            linkageStartStop.setDisable(linkageBean.isDisable());
            linkageStartStops.add(linkageStartStop);
        }
        mLinkageStartStops = linkageStartStops;
        switch (type){
            case AddTaskActivity.TYPE_LINKAGE:
                //当前联动空，才去
                if (mLinkageTask == null) {
                    //本地保存联动条件
                    if (mLinkageBean == null) {
                        mLinkageBean = new LinkageNewBean();
                        LinkageDataHolder.setLinkageDataNew(mLinkageBean);
                    }
                    List<LinkageBean.LinkageTask> linkageTasks = mLinkageBean.getLinkageTasks();
                    if (linkageTasks == null) {
                        linkageTasks = new ArrayList<>();
                    }
                    mLinkageBean.setLinkageTasks(linkageTasks);
                    mLinkageTask = new LinkageBean.LinkageTask();
                    //先设置个本地的SerialNo，为了编辑找到对应的数据
                    mLinkageTask.setTaskSerialNo(UUID.randomUUID().toString());
                    mLinkageTask.setTaskType(4);
                    if(mPosition < 0){
                        linkageTasks.add(mLinkageTask);
                    }else{
                        linkageTasks.add(mPosition, mLinkageTask);
                    }
                }
                mLinkageTask.setLinkageStartStop(mLinkageStartStops);
                mLinkageTask.setImageUrl("icon_intelligent_linkage");
                mLinkageTask.setBriefing("联动启停");
                startActivity_SingleTask(EditLinkageActivityNew.class);
                break;
            case AddTaskActivity.TYPE_SCENE:
                //当前场景空，才去
                if (mSceneTask == null) {
                    //本地保存联动条件
                    if (mSceneDetailBean == null) {
                        mSceneDetailBean = new SceneDetailBean();
                        TempDataHolder.setEditSceneDetailBean(mSceneDetailBean);
                    }
                    List<SceneDetailBean.SceneTaskBean> sceneTasks = mSceneDetailBean.getSceneTasks();
                    if (sceneTasks == null) {
                        sceneTasks = new ArrayList<>();
                    }
                    mSceneDetailBean.setSceneTasks(sceneTasks);
                    mSceneTask = new SceneDetailBean.SceneTaskBean();
                    //先设置个本地的SerialNo，为了编辑找到对应的数据
                    mSceneTask.setSceneTaskSerialNo(UUID.randomUUID().toString());
                    mSceneTask.setSceneTaskType(4);
                    if(mPosition < 0){
                        sceneTasks.add(mSceneTask);
                    }else{
                        sceneTasks.add(mPosition, mSceneTask);
                    }
                }
                mSceneTask.setLinkageStartStops(mLinkageStartStops);
//                mSceneTask.setTaskBriefing(LLSceneLinkageUtil.makeTaskBriefing(mSceneTask));
                mSceneTask.setImage("icon_intelligent_linkage");
                mSceneTask.setName("联动启停");
                switch (sceneType){
                    case 1:
                        startActivity_SingleTask(EditSceneActivityNew.class);
                        break;
                    case 3:
                        startActivity_SingleTask(EditSceneIntentActivity.class);
                        break;
                    case 4:
                        startActivity_SingleTask(EditScenePrivateActivity.class);
                        break;
                }
                break;
        }
        finish();
    }

    private void showBottomListDialog() {
        if (mBottomListDialog == null) {
            mBottomListDialog = new BottomListDialog(this);
            ListLabelAdapter listLabelAdapter = new ListLabelAdapter(this);
            List<String> data = new ArrayList<>();
            data.add(getString(R.string.start_using));
            data.add(getString(R.string.stop_using));
            listLabelAdapter.setData(data);
            listLabelAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
                    String name = listLabelAdapter.getSelected();
                    if(isSet){
                        if(setStartStopLinkage != null){
                            if(getString(R.string.start_using).equals(name)){
                                setStartStopLinkage.setDisable(false);
                            }else{
                                setStartStopLinkage.setDisable(true);
                            }
                        }
                        mSetLinkageAdapter.notifyDataSetChanged();
                    }else{
                        if(notSetStartStopLinkage != null){
                            if(getString(R.string.start_using).equals(name)){
                                notSetStartStopLinkage.setDisable(false);
                            }else{
                                notSetStartStopLinkage.setDisable(true);
                            }
                        }
                        mNotSetLinkageAdapter.putSelected(notSetStartStopLinkage);
                        if(editSearch.getText().length() > 0){
                            searchSetLinkage(editSearch.getText().toString());
                        }else{
                            mSetLinkageAdapter.setData(mNotSetLinkageAdapter.getSelectedData());
                            isShowSetLinkageLayout();
                        }
                    }
                    mBottomListDialog.dismiss();
                }
            });
            mBottomListDialog.setAdapter(listLabelAdapter);
            new XPopup.Builder(this)
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(mBottomListDialog);
        }
        ListLabelAdapter listLabelAdapter = (ListLabelAdapter) mBottomListDialog.getAdapter();
        if(isSet && setStartStopLinkage != null){
            listLabelAdapter.checkSelected(setStartStopLinkage.isDisable() ? getString(R.string.stop_using) : getString(R.string.start_using));
        }else{
            listLabelAdapter.checkSelected(null);
        }
        mBottomListDialog.show();
    }
}